package com.darren.euc.interceptor;

import com.darren.euc.entity.Member;
import com.darren.euc.entity.ResponseJSON;
import com.darren.euc.service.MemberService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * app未登录拦截
 * Created by JUECHENG at 2018/3/12 12:28.
 */
@SuppressWarnings("Duplicates")
public class AppLoginInterceptor implements HandlerInterceptor {
    private static final Log log = LogFactory.getLog(AppLoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        ResponseJSON bean = new ResponseJSON();
        //header和参数中都不带有token 未登录（参数中的token为方便调试代码所添加）
        Member member = (Member) request.getAttribute("member");
        if (member == null) {
            bean.set(-2, "访问失败，用户未登录");
            return ajax(JSONObject.fromObject(bean).toString(),response);
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {

    }

    //下面代码拷贝于TokenInterceptor
    private boolean ajax(String content, HttpServletResponse response) {
        try {
            response.setContentType("application/json;charset=UTF-8");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.getWriter().write(content);
            response.getWriter().flush();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }
}
